package com.example.securityproject.demos.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.securityproject.demos.common.BusinessException;
import com.example.securityproject.demos.entity.User;
import com.example.securityproject.demos.utils.JwtUtils;
import com.example.securityproject.demos.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

//    @Resource
//    private RedisTemplate redisTemplate;

    @Resource
    private RedisUtils redisUtils;

    private static final String USER_PREFIX = "login:";

    public TokenAuthenticationFilter () {
        super();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        //获取token
        String token = req.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            chain.doFilter(req, res);
            return;
        }
        //解析token
        String userid;
        List<GrantedAuthority> authorities = new ArrayList<>();
        try {
            Claims claims = JwtUtils.parseToken(token);
            userid = claims.get("userId").toString();
            String authoritiesStr = claims.get("authorities").toString();
            JSONArray jsonArray = JSON.parseArray(authoritiesStr);
            authorities = jsonArray.toJavaList(GrantedAuthority.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String redisKey = USER_PREFIX + userid;
        User user = (User) redisUtils.get(redisKey);
//        User user = (User) redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户未登录");
        }
//        String userName = user.getUsername();
        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, token, authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        chain.doFilter(req, res);
    }
}
